from zope.interface import implements
from twisted.internet import reactor
from twisted.web import xmlrpc, server
import os, sys

APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)

from watcher import WatcherContainer
from watcher.interfaces import IWatch
from watcher.config import ConfigLoader, DEFAULT_CONFIG_PATH
from watcher.inputqueue import inputQueue
from watcher.branch import Branch

class Watch(WatcherContainer):
    """watch process"""
    implements(IWatch)

    def __init__(self, *args, **kwargs):
       super(Watch, self).__init__(*args, **kwargs)
       queue = self.config.input_queue.type + "_" + self.config.input_queue.name
       self.queue = inputQueue(queue, self.configPath)
       self.branches = []
       for branch in self.config.branch:
           self.branches.append(Branch("branch_" + branch.name, self.configPath, parent = self))

    
    def run(self, workItem):
        """watch must be able to run against a work item"""
        for branch in self.branches:
            branch.execute_path.execute(workItem)
        self.final(workItem)
    
    
    def final(self, workItem):
        if self.config.final.xml_text_content().lower() == "clean":
            os.unlink(workItem)        
